package com.example.jwtauthdemo.controller;

import com.example.jwtauthdemo.dao.Student;
import com.example.jwtauthdemo.entity.CreateClass;
import com.example.jwtauthdemo.model.User;
import com.example.jwtauthdemo.service.AuthService;
import com.example.jwtauthdemo.service.ClassService;
import com.example.jwtauthdemo.service.StudentManageService;
import com.example.jwtauthdemo.util.Result;
import com.example.jwtauthdemo.util.ResultCode;
import com.example.jwtauthdemo.dto.LoginRequest;
import com.example.jwtauthdemo.dto.RegisterRequest;
import jakarta.validation.Valid;

import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthService authService;
    private final ClassService classService;
    private final StudentManageService studentManageService;

    public AuthController(AuthService authService, ClassService classService, StudentManageService studentManageService) {
        this.authService = authService;
        this.classService = classService;
        this.studentManageService = studentManageService;
    }

    // 用户注册
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@Valid @RequestBody RegisterRequest registerRequest) {
        try {
            User user = authService.register(registerRequest);
            // 注册成功后自动登录生成令牌
            LoginRequest loginRequest = new LoginRequest();
            loginRequest.setUsername(registerRequest.getUsername());
            loginRequest.setPassword(registerRequest.getPassword());
            String token = authService.login(loginRequest);
            Map<String, Object> response = new HashMap<>();
            response.put("user", user);
            response.put("token", token);
            return Result.success(response);
        } catch (RuntimeException e) {
            return Result.error(ResultCode.BUSINESS_ERROR, e.getMessage());
        }
    }

    // 用户登录
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            String token = authService.login(loginRequest);
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);

            // 获取用户信息，添加role字段
            User user = authService.getCurrentUser();
            response.put("role", user.getRole());
            // 添加real_name字段
            response.put("real_name", user.getRealName());
            // 添加教师id字段
            response.put("teacher_id", user.getId());
            
            // 添加班级名字name字段（仅对教师和管理员角色）
            if (user.getRole() == 1 || user.getRole() == 2) {
                try {
                    List<CreateClass> classes;
                    if (user.getRole() == 2) {
                        // 班主任角色：直接查询其创建的班级
                        classes = classService.selectClassesByTeacherId(user.getId().toString());
                    } else {
                        // 老师角色：通过user_class_relation表查询关联的班级
                        classes = classService.selectClassesByUserIdAndRole(user.getId().toString(), user.getRole());
                    }
                    
                    // 如果有班级，取第一个班级的名称
                    if (classes != null && !classes.isEmpty()) {
                        response.put("name", classes.get(0).getName());
                        
                        // 尝试获取该班级的学生列表
                        try {
                            String classCode = classes.get(0).getClassCode();
                            List<Student> students = studentManageService.selectStudentInfo(classCode, user.getId().toString());
                            
                            // 提取学生id列表和名字列表
                            List<String> studentIds = new ArrayList<>();
                            List<String> studentNames = new ArrayList<>();
                            
                            if (students != null && !students.isEmpty()) {
                                for (Student student : students) {
                                    studentIds.add(student.getStudentId());
                                    studentNames.add(student.getRealName());
                                }
                            }
                            
                            response.put("student_ids", studentIds);
                            response.put("student_names", studentNames);
                        } catch (Exception e) {
                            // 如果获取学生列表失败，不影响登录成功
                            System.out.println("获取学生列表失败: " + e.getMessage());
                        }
                    }
                } catch (Exception e) {
                    // 如果获取班级信息失败，不影响登录成功
                    System.out.println("获取班级信息失败: " + e.getMessage());
                }
            }

            System.out.println( response.get("token"));
            return Result.success(response);
        } catch (Exception e) {
            return Result.error(ResultCode.UNAUTHORIZED, "用户名或密码错误");
        }
    }


    // 获取当前用户信息
    @GetMapping("/me")
    public Result<Map<String, Object>> getCurrentUserInfo() {
        try {
            User user = authService.getCurrentUser();
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("phone", user.getPhone());
            userInfo.put("nickname", user.getNickname());
            userInfo.put("avatar", user.getAvatar());
            userInfo.put("gender", user.getGender());
            userInfo.put("age", user.getAge());
            userInfo.put("real_name", user.getRealName());
            userInfo.put("email", user.getEmail());
            return Result.success(userInfo);
        } catch (Exception e) {
            return Result.error(ResultCode.UNAUTHORIZED, "未授权访问");
        }
    }

}
    